package cn.hiapi.core.basic.sharding.utils;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author AdinZ
 * @date 2024/1/9 18:10
 */
public class DatabaseUtils {


    /**
     * 查询全部分表
     *
     * @param dataSource 数据源
     * @param table      表名开头
     * @return 全部表名
     */
    public static Set<String> queryTables(DataSource dataSource, String table) {
        Pattern monthPattern = Pattern.compile("^" + table + "_[0-9]{6}$");
        try (Statement statement = dataSource.getConnection().createStatement()) {
            ResultSet resultSet = statement.executeQuery("show tables like '" + table + "_%'");
            Set<String> tables = new LinkedHashSet<>();
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                if (monthPattern.matcher(tableName).matches()) {
                    tables.add(tableName);
                }
            }
            return tables;
        } catch (SQLException e) {
            e.printStackTrace();
            return new HashSet<>();
        }
    }


    public static boolean createTable(DataSource dataSource,String logicTable, String createTable) throws SQLException {
        String sql = "CREATE TABLE " + createTable + " LIKE " + logicTable;
        try (Statement statement = dataSource.getConnection().createStatement()) {
          return    statement.execute(sql);
        }
    }
}
